package com.atguigu.controller;

import com.atguigu.controller.base.ModelBaseServlet;
import com.atguigu.pojo.BookstoreConstant;
import com.atguigu.pojo.Cart;
import com.atguigu.pojo.User;
import com.atguigu.service.OrderService;
import com.atguigu.service.impl.OrderServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author luoyin
 * @Date 11:27 2022/7/23
 **/
@WebServlet("/protect/orderClient")
public class OrderClientController extends ModelBaseServlet {
    //去订单结算页面
    public void toCheckOutPage(HttpServletRequest request, HttpServletResponse response){
        try {
            processTemplate("pages/cart/checkout",request,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //订单结算
    public void checkOut(HttpServletRequest request, HttpServletResponse response){
        //用户id
        User existUser = (User) request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_USER);
        //购物车
        Cart existCart = (Cart) request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_CART);

        OrderService orderService= new OrderServiceImpl();
        try {
            String orderSequence = orderService.checkOut(existCart, existUser);
            if (orderSequence != null){
                request.getSession().removeAttribute(BookstoreConstant.SESSION_KEY_CART);
            }
            request.getSession().setAttribute(BookstoreConstant.SESSION_KEY_ORDERSEQUENCE,orderSequence);
            response.sendRedirect(request.getContextPath()+"/protect/orderClient?method=toCheckOutPage");
            /*if(orderSequence != null){
                request.getSession().setAttribute(BookstoreConstant.SESSION_KEY_ORDERSEQUENCE,orderSequence);
                response.sendRedirect(request.getContextPath()+"/protect/orderClient?method=toCheckOutPage");
            }else {
                request.getRequestDispatcher("/protect/cart?method=toCartPage").forward(request,response);
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
